<template>
<div class="app-container">
    <el-row class="row">
        <el-col :span="12">
            <div class="grid-content bg-purple-dark">
                <el-button v-if="tabE!=2" type="primary" icon="el-icon-circle-plus" @click="videoSave">新增</el-button>
                <el-button v-if="tabE==0" type="primary" icon="el-icon-delete-solid" @click="bindVideo">推荐</el-button>
                <el-button v-if="tabE==1" type="primary" icon="el-icon-delete-solid" @click="bindVideo">取消推荐</el-button>
                <el-button v-if="tabE!=2" type="primary" icon="el-icon-delete-solid" @click="deleteVideo">下架</el-button>
                <el-button v-if="tabE==2" type="primary" icon="el-icon-delete-solid" @click="deleteVideo">还原</el-button>
            </div>
    </el-col>
    </el-row>
    <!-- 视频管理列表 -->
    <el-table
    v-loading="loading"
    :data="videoData"
    border
    style="width: 100%"
    @selection-change="handleVideoChange"
    height="380">
    <el-table-column
      fixed
      prop="date"
      width="50"
      type="selection"
      align="center">
    </el-table-column>
    <el-table-column
      fixed
      prop="videoId"
      label="视频编号"
      width="150"
      align="center">
    </el-table-column>
    <el-table-column
      prop="videoDesc"
      label="视频文案"
      width="200"
      align="center">
      <template slot-scope="scope">
        <div v-if="scope.row.videoDesc.length > 5">
          <div class="ellipsis" v-tooltip :content="scope.row.videoDesc">
            <el-popover
              placement="top-start"
              width="200"
              trigger="hover"
              :content="scope.row.videoDesc">
              <span slot="reference">{{ scope.row.videoDesc }}</span>
            </el-popover>
          </div>
        </div>
        <div v-else>{{ scope.row.videoDesc }}</div>
      </template>
    </el-table-column>
    <el-table-column
      label="视频封面"
      width="120"
      align="center">
      <template slot-scope="scope">
        <el-image style="width: 95px; height: 95px" @click="onImage(scope.row.coverNumber)" :src="`http://101.43.223.224:8765/image/getImageById?id=${scope.row.coverNumber}`" :preview-src-list="srcList"></el-image>
      </template>
    </el-table-column>
    <el-table-column
      label="播放视频"
      width="120"
      align="center">
      <template slot-scope="scope">
        <el-button type="primary" @click="onVideo(scope.row.videoNumber)" icon="el-icon-video-play">播放</el-button>
      </template>
    </el-table-column>
    <el-table-column
      label="视频状态"
      width="120"
      align="center">
      <template slot-scope="scope">
        <el-tag type="success" v-if="scope.row.videoStatus=='公开'">{{ scope.row.videoStatus }}</el-tag>
        <el-tag type="info" v-else>{{ scope.row.videoStatus }}</el-tag>
      </template>
    </el-table-column>
    <el-table-column
      prop="videoTopic"
      label="视频话题"
      width="180"
      align="center">
      <template slot-scope="scope">
        <div v-for="(item,index) in scope.row.videoTopic.split(',')" :key="index">
          <el-tag style="margin-top:5px">{{ item }}</el-tag>
        </div>
      </template>
    </el-table-column>
    <el-table-column
      prop="userId"
      label="上传者编号"
      width="120"
      align="center">
    </el-table-column>
    <el-table-column
      prop="userAccount"
      label="上传账号"
      width="120"
      align="center">
    </el-table-column>
    <el-table-column
      prop="creationTime"
      label="上传时间"
      width="160"
      align="center">
    </el-table-column>
    <el-table-column
      prop="videoWidth"
      label="视频宽度(rpx)"
      width="120"
      align="center">
    </el-table-column>
    <el-table-column
      prop="videoHeight"
      label="视频高度(rpx)"
      width="120"
      align="center">
    </el-table-column>
    <el-table-column
      fixed="right"
      label="操作"
      width="120"
      align="center">
      <template slot-scope="scope">
        <el-button v-if="tabE!=2" @click="videoDetails(scope.row)" type="text" size="small">详情</el-button>
        <el-button v-if="tabE!=2" type="text" @click="videoUpdate(scope.row)" size="small">编辑</el-button>
        <el-button v-if="tabE==0" type="text" @click="bindVideo(scope.row)" size="small">推荐</el-button>
        <el-button v-if="tabE!=2" type="text" @click="deleteVideo(scope.row)" size="small">下架</el-button>
        <el-button v-if="tabE==1" type="text" @click="bindVideo(scope.row)" size="small">取消推荐</el-button>
        <el-button v-if="tabE==2" @click="deleteVideo(scope.row)" type="text" size="small">还原</el-button>
      </template>
    </el-table-column>
  </el-table>
  <!---分页-->
    <el-pagination
        @current-change="handleVideoCurrentChange"
        @size-change="handleVideoSizeChange"
        :current-page="videoParams.pageNum"
        :page-sizes="[3, 5, 10, 20]"
        :page-size="videoParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        background
    :total="videoParams.total"
        class="page">
    </el-pagination>

    <div class="videoDiv1" v-if="dialogVideoVisible==true">
      <a @click="CloseV" class="vIcon1 el-icon-circle-close"></a>
      <video-player class="videoPlayer vjs-custom-skin" ref="videoPlayer" :options="Options">
      </video-player>
    </div>

    <el-drawer :title="titleDra" :visible.sync="dialogVideoFormVisible" @close="handleDialog2Close" direction="ttb" size="100%" :style="{ width: '87%', height: '100%',margin:'0% 13%' }">
      <div class="item-button">
        <el-button @click="cancelVideo">取 消</el-button>
        <el-button type="primary" @click="addVideo">确 定</el-button>
      </div>
      <div class="yshz">
      <el-form :model="videoForm" :rules="videoFormRules" ref="videoForm" label-width="180px" class="itemFm">
        <el-form-item label="发布账号" prop="userAccount" class="itemZ">
          <el-select v-model="videoForm.userAccount" placeholder="选择发布账号">
            <el-option label="wzpnb666" value="wzpnb666"></el-option>
            <el-option label="genshin" value="genshin"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="视频封面" class="item2">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:7888/PublishVideo/uploadVideoCover"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            >
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="上传视频" class="item2">
          <el-upload
            class="upload-demo"
            action="http://localhost:7888/PublishVideo/uploadVideo"
            :on-success="handleVideoSuccess"
            :before-upload="beforeVideoUpload">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传mp4格式视频，且不超过1mb（服务器最大上传上限1mb）</div>
          </el-upload>
          <video-player class="video-player1 vjs-custom-skin" ref="videoPlayer1" v-if="videoId" :options="computedOptions">
          </video-player>
        </el-form-item> 
        <el-form-item label="视频文案" prop="videoDesc" class="item3">
          <el-input type="textarea" v-model="videoForm.videoDesc" :rows="4" style="width:350px"></el-input>
        </el-form-item>
        <el-form-item label="视频标签" prop="videoTopic" class="item">
          <el-cascader
            v-model="topic"
            placeholder="选择视频标签"
            :options="options"
            :props="{ multiple: true }"
            filterable>
          </el-cascader>
        </el-form-item>
        <el-form-item label="公开/隐藏" prop="videoStatus" class="item">
          <el-radio-group v-model="videoForm.videoStatus" size="small">
            <el-radio label="公开" border>公开视频</el-radio>
            <el-radio label="隐藏" border>隐藏视频</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      </div>
    </el-drawer>

    <el-drawer
      title="视频详情"
      :visible.sync="DetailsVisible"
      direction="rtl"
      size="50%"
      :before-close="handleClose">
      <el-table :data="detailsData">
        <el-table-column property="videoId" align="center" label="视频编号" width="130"></el-table-column>
        <el-table-column property="vid" align="center" label="视频ID" width="90"></el-table-column>
        <el-table-column property="userId" align="center" label="发布者ID" width="90"></el-table-column>
        <el-table-column property="userAccount" align="center" label="发布者昵称" width="90"></el-table-column>
        <el-table-column property="likeCounts" align="center" label="点赞数" width="90"></el-table-column>
        <el-table-column property="collectCounts" align="center" label="收藏数" width="90"></el-table-column>
        <el-table-column property="commentCounts" align="center" label="评论数" width="90"></el-table-column>
        <el-table-column property="videoViews" align="center" label="浏览量" width="90"></el-table-column>
        <el-table-column property="shareVolume" align="center" label="分享量" width="90"></el-table-column>
        <el-table-column property="download" align="center" label="下载量" width="90"></el-table-column>
      </el-table>
      <!---分页-->
      <el-pagination
        @current-change="handleDetailsCurrentChange"
        @size-change="handleDetailsSizeChange"
        :current-page="detailsParams.pageNum"
        :page-sizes="[3, 5, 10, 20]"
        :page-size="detailsParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        background
        :total="detailsParams.total"
        class="page2">
      </el-pagination>
    </el-drawer>
</div>
</template>

<script>
import {listData,listDataT,listDataX,delData,bindData,listDataById,addData,updateData,delVideoById,deleteVideoCoverById} from '@/api/video/video';
import {topicqueryAll} from "@/api/topic/topic";
import { Tooltip } from 'element-ui';
export default {
  directives: {
    tooltip: Tooltip
  },
    props: ['vdData','totalS','tabE','refreshFlag'],
    data() {
      return {
        //视频列表容器
        videoData:[],
        //视频话题容器
        topicData:[],
         // 遮罩层
        loading: true,
        //查询参数集合
        videoParams:{
            pageNum:1,
            pageSize:3,
            total:0,
        },
        //videoData多选框选中的值
        videoIds:[],
        //新增/编辑弹窗遮罩层
        dialogVideoFormVisible:false,
        //视频封面弹出框遮罩层
        dialogCoverVisible:false,
        //视频弹出框遮罩层
        dialogVideoVisible:false,
        //新增视频form标题盒子宽度
        formLabelWidth: '140px',
        //新增、编辑弹窗标题
        titleDra:'',
        //新增/编辑参数
        videoForm: {
          vId:'',
          userAccount: '',
          coverNumber: '',
          videoNumber: '',
          videoDesc: '',
          videoTopic: '',
          videoStatus: ''
        },
       
        videoFormRules: {
          userAccount: [
            { required: true, message: '请选择发布账号', trigger: 'blur' }
          ],
          videoStatus: [
            { required: true, message: '请选择视频状态', trigger: 'blur' }
          ],
        },

        //回显话题
        topic:[],

        //视频详情列表
        detailsData:[],

        //视频详情列表分页参数集合
        detailsParams:{
          pageNum:1,
          pageSize:3,
          total:0,
        },

        //详情列表遮罩层
        DetailsVisible:false,

        //视频封面地址
        imageUrl: '',

        //视频、视频封面删除标识
        delFlag:0,

        //视频标签列表
        options: [],

        //视频封面放大
        srcList:[],

        //视频回显Id
        videoId:'',

        //视频回显id
        videoShowId:'',

        //视频配置
        playerOptions: {
          // 视频 url
          sources: [{
            
          }],
          // 其他设置项
          controls: true,
          preload: "auto",
          aspectRatio: "16:9",
          fluid: true,
          // poster: 'http://101.43.223.224:8765/image/getImageById?id='+6613,
          notSupportedMessage: "此视频暂无法播放，请稍后再试", // 允许覆盖Video.js无法播放媒体源时显示的默认信息
        },

        //视频配置
        playerO: {
          // 视频 url
          sources: [{
            
          }],
          // 其他设置项
          controls: true,
          preload: "auto",
          aspectRatio: "16:9",
          fluid: true,
          // poster: 'http://101.43.223.224:8765/image/getImageById?id='+6613,
          notSupportedMessage: "此视频暂无法播放，请稍后再试", // 允许覆盖Video.js无法播放媒体源时显示的默认信息
        },
      }
    },
    created(){
      //渲染视频列表
      this.getPublishVideo();
      //话题回显
      this.topicSelect();
      //放大视频封面
      this.onImage()
    },
    methods:{
      //上传视频列表分页操作
      handleVideoSizeChange(pageSize) {
        this.videoParams.pageSize = pageSize
        this.getPublishVideo()
      },
      handleVideoCurrentChange(pageNum) {
        this.videoParams.pageNum = pageNum
        this.getPublishVideo()
      },

       //视频详情列表分页操作
       handleDetailsSizeChange(pageSize) {
        this.detailsParams.pageSize = pageSize
      },
      handleDetailsCurrentChange(pageNum) {
        this.detailsParams.pageNum = pageNum
      },

      //查询运营视频
      getPublishVideo(){
        this.loading = true;
        if(this.tabE==0){
          listData(this.videoParams).then(res =>{
            this.videoData = []
            this.videoData = res.data.data.content;
            this.videoParams.total = res.data.data.totalSize;
            this.loading = false;
            
          })
        }else if(this.tabE==1){
          listDataT(this.videoParams).then(res =>{
            this.videoData = []
            this.videoData = res.data.data.content;
            this.videoParams.total = res.data.data.totalSize;
            this.loading = false;
          })
        }else{
          listDataX(this.videoParams).then(res =>{
            this.videoData = []
            this.videoData = res.data.data.content;
            this.videoParams.total = res.data.data.totalSize;
            this.loading = false;
          })
        }
        
      },

      //放大视频封面
      onImage(coverNumber){
        this.srcList.push("http://101.43.223.224:8765/image/getImageById?id="+coverNumber)
      },

      //播放按钮
      onVideo(videoNumber){
        this.dialogVideoVisible=true;
        this.videoShowId = videoNumber;
      },

      //视频弹出框关闭后操作
      CloseV(){
        this.dialogVideoVisible=false;
      },

      //新增编辑弹出框关闭后操作
      handleDialog2Close(){
        this.playerOptions.sources.splice(0, 1);
        if(this.delFlag == 0 &&  this.imageUrl){
          deleteVideoCoverById(this.videoForm.coverNumber)
        }
        if(this.delFlag == 0 &&  this.videoId){
          delVideoById(this.videoId)
        }
        this.resetForm();
        this.delFlag = 0
      },

      // 上传视频列表多选框
      handleVideoChange(val){
        this.videoIds = val.map(v=>v.vid)
      },

      //删除视频
      deleteVideo(row){
        if(this.videoIds.length==0 && !row.vid){
          this.$message({
          message: '请先勾选需要操作数据',
          type: 'warning'
          });
        }else{
          let vids = [row.vid]
          let videoIds =[]
          if(this.videoIds.length>0){
            videoIds = this.videoIds
          }else{
            videoIds = vids
          }
          this.$modal.confirm('是否操作选中的这' + videoIds.length + '条数据项？').then(function() {
          return delData(videoIds);
        }).then(res =>{
          if(res.flag==true){
            this.getPublishVideo()
            this.$modal.msgSuccess("删除成功");
          }else{
            this.$modal.msgError("删除失败")
          }
          })
        }
      },

      //绑定视频池（推荐、取消推荐
      bindVideo(row){
        if(this.videoIds.length==0 && !row.vid){
          this.$message({
          message: '请先勾选需要操作数据',
          type: 'warning'
          });
        }else{
          let vids = [row.vid]
          let videoIds =[]
          if(this.videoIds.length>0){
            videoIds = this.videoIds
          }else{
            videoIds = vids
          }
          this.$modal.confirm('是否操作选中的这' + videoIds.length + '条视频？').then(function() {
          return bindData(videoIds);
        }).then(res =>{
          if(res.flag==true){
            this.getPublishVideo()
            this.$modal.msgSuccess("操作成功");
          }else{
            this.$modal.msgError("操作失败")
          }
          })
        }
      },

      //打开新增窗口
      videoSave(){
        this.titleDra = '新增视频'
        this.dialogVideoFormVisible = true;
      },

      //打开编辑视频弹窗
      videoUpdate(row){
        this.titleDra = '编辑视频'
        this.dialogVideoFormVisible = true
        this.videoForm = row
        this.topic = row.videoTopic.split(',')
        this.imageUrl = 'http://101.43.223.224:8765/image/getImageById?id='+row.coverNumber
        this.videoId = row.videoNumber
      },

      // 新增/编辑视频弹窗
      addVideo(){
        if(this.videoForm.vId==''){
          if(this.videoForm.userAccount){
            if(this.videoForm.coverNumber){
              if(this.videoForm.videoNumber){
                if(this.videoForm.videoStatus){
                  this.delFlag = 1
                  this.dialogVideoFormVisible = false
                  if(this.topic){
                    const tc = this.topic.join(',');
                    this.videoForm.videoTopic = tc; 
                  }
                  addData(this.videoForm).then(res =>{
                    if(res.flag == true){
                      this.getPublishVideo()
                      this.$modal.msgSuccess("新增成功");
                      this.resetForm
                      this.imageUrl = ''
                      this.videoId = ''
                    }else{
                      this.$modal.msgError("新增失败")
                      this.resetForm
                      this.imageUrl = ''
                      this.videoId = ''
                    }
                  })
                }else{
                  this.$message('请选择视频状态')
                }
              }else{
                this.$message('请上传视频')
              }
            }else{
              this.$message('请上传视频封面')
            }
          }else{
            this.$message('请选择发布账号')
          }
        }else{
          this.dialogVideoFormVisible = false
          if(this.topic){
            const tc = this.topic.join(',');
            this.videoForm.videoTopic = tc; 
          } 
          updateData(this.videoForm).then(res =>{
            if(res.flag == true){
              this.getPublishVideo()
              this.$modal.msgSuccess("编辑成功");
              this.resetForm
              this.imageUrl = ''
              this.videoId = ''
            }else{
              this.$modal.msgError("编辑失败")
              this.resetForm
              this.imageUrl = ''
              this.videoId = ''
            }
          })
        }
      },

      //新增/编辑取消按钮
      cancelVideo(){
        this.dialogVideoFormVisible = false
      },

      //清空form表单
      resetForm() {
        this.videoForm= {
          vId:'',
          userAccount: '',
          coverNumber: '',
          videoNumber: '',
          videoDesc: '',
          videoTopic: '',
          videoStatus: ''
        }
        this.videoId = ''
        this.imageUrl = ''
        this.topic = ''
      },

      // 查询视频详情
      videoDetails(row){
        this.DetailsVisible = true;
        const vid = row.vid
        listDataById(vid).then(res =>{
          this.detailsData = res.data.data.content;
          this.detailsParams.total = res.data.data.totalSize;
        })
      },

      //查询话题（新增窗口话题下拉框）
      topicSelect(){
        topicqueryAll().then(res =>{
          this.topicData = res.data
          this.topicData.forEach(item => {
            const options = {
              value:item.topicName,
              label:item.topicName
            }
            this.options.push(options)
          });
        })
      },

      //新增弹窗关闭提示
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },

      // 视频封面上传之后操作
      handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
        console.log("图片地址"+this.imageUrl);
        this.videoForm.coverNumber = res.data;
        console.log("图片回显ID"+this.videoForm.coverNumber);
      },

      // 视频封面上传之前操作
      beforeAvatarUpload(file) {
        if(this.imageUrl){
          deleteVideoCoverById(this.videoForm.coverNumber)
        }
        const isPNG = file.type === 'image/png';
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isPNG || !isJPG) {
          this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isPNG && isLt2M;
      },

      // 视频上传之后操作
      handleVideoSuccess(res,file){
        this.videoId = res.data;
        this.videoForm.videoNumber = res.data;
        console.log("视频回显Id"+this.videoId);
      },

      // 视频上传之前操作
      beforeVideoUpload(){
        if(this.videoId){
          delVideoById(this.videoForm.videoNumber)
        }
      },
    },
    
    computed: {
      //播放视频路径
      computedOptions() {
        if (this.videoId) {
          if(this.playerOptions.sources.length>0){
            this.playerOptions.sources.splice(0, 1);
          }
          this.playerOptions.sources.push({
            src: 'http://101.43.223.224:8765/image/getVideoById?id='+this.videoId,
            type: 'video/mp4',
          });
          return this.playerOptions;
        } else {
          return {}
        }
      },

      //播放视频路径
      Options() {
        if (this.videoShowId) {
          if(this.playerO.sources.length>0){
            this.playerO.sources.splice(0, 1);
          }
          this.playerO.sources.push({
            src: 'http://101.43.223.224:8765/image/getVideoById?id='+this.videoShowId,
            type: 'video/mp4',
          });
          return this.playerO;
        } else {
          return {}
        }
      },
  },

  watch:{
    // 模糊查数据条数
    totalS(newVal) {
      this.videoParams.total = newVal; // 监听totalS的变化，将新值赋给totalSize
    },
    vdData(newVal){
      this.videoData = newVal;
    },
    refreshFlag: function(newVal, oldVal) {
        if (newVal) {
            // 调用重新加载表格数据的方法
            this.getPublishVideo();
        }
    }
  }
}
</script>

<style lang="less" scoped>
.row{
    margin-bottom: 10px;
  }
.page{
    margin-top: 15px;
    margin-left: 360px;
}

.page2{
  position: absolute;
	  bottom: 50px;
	  left: 160px;
}

.videoDiv1{
  width:500px;
  height:280px;
  position: fixed;
  bottom: 320px;
  right: 430px;
}

.vIcon1{
  font-size: 22px;
  color:rgba(249, 249, 249, 0.801);
  float: right;
  position: relative;;
  top: 5px;
  right: 5px;
  z-index: 1;
}

.ellipsis {
  width: 160px; /* 根据实际情况调整宽度 */
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin:0 auto;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 240px;
  display: inline-block;
  z-index: 1;
}
.avatar-uploader:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 240px;
  line-height: 240px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 240px;
  display: inline-block;
}
.item-button{
  width:200px;
  float: right;
  margin-right:100px;
  margin-top:10px;
}
.item{
  float: left;
  width:420px;
}
.itemZ{
  width:420px;
}
.item2{
  float: left;
  width:420px;
}

.item3{
  width:420px;
}
.yshz{
  width: 1100px;
  height:600px;
  margin-top:40px;
  margin-left:160px;
}
.itemFm{
  width: 1100px;
  height:600px;
}
.video-player1 {
  width:400px;
  margin-right:100px;
}
</style>